package a66weding.com.jiehuntong.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.transition.Explode;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;

import a66weding.com.jiehuntong.MainActivity;
import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.User;
import a66weding.com.jiehuntong.beans.VerifiCodeLoginBean;
import a66weding.com.jiehuntong.common.MyActivityManager;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.CacheUtils;
import a66weding.com.jiehuntong.common.utils.MD5Util;
import a66weding.com.jiehuntong.common.utils.Utils;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.NetStatusUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * 文件作用：新版本短信快速登录页面
 */
public class SMSFastLoginActivity extends AppCompatActivity implements View.OnClickListener, OnNetResultListener {
    private TextView tv_smsfast_login_getverficode;
    private TextInputEditText tiet_smsfast_login_phonenumber;
    private TextInputLayout til_smsfast_login_phonenumber;
    private TextInputEditText tiet_smsfast_login_verficode;
    private TextInputLayout til_smsfast_login_verficode;
    private Button btn_smsfast_login;
    private TextView tv_password_login;
    private ImageButton imgbtn_smsfast_login_qq;
    private ImageButton imgbtn_smsfast_login_wechat;
    private ImageButton imgbtn_smsfast_login_sina;
    private RelativeLayout activity_smsfast_login;
    private int time = 60;//短信倒计时
    private static final int LOGINBTN = 1;
    private boolean isCanClickable = true;//是否能点击防止瞬间用户多次点
    private static final int WHAT_EXIT_FLAG = 0x128;//两次退出使用
    private final int RESETTEXT = 11;//点击获取验证码后就发送后倒计时
    private final int GETVERIFIFAIL = 12;//获取验证码失败，需要重置
    private boolean isCanBack;//是否返回登录的上一个界面
    private boolean mExitFlag;
    public static int LOGIN_OK = 200;
    public static int PSWLOGIN = 600;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOGINBTN:
                    isCanClickable = true;
                    break;
                case WHAT_EXIT_FLAG:
                    if (null != SMSFastLoginActivity.this) {
                        SMSFastLoginActivity.this.mExitFlag = false;
                    }
                    break;
                case GETVERIFIFAIL://获取验证码失败
                    mHandler.removeMessages(RESETTEXT);
                    tv_smsfast_login_getverficode.setText(R.string.huoquyanzhen);
                    tv_smsfast_login_getverficode.setEnabled(true);
                    time = 60;
                    break;
                case RESETTEXT:
                    tv_smsfast_login_getverficode.setText("" + time--);
                    tv_smsfast_login_getverficode.setTextColor(getResources().getColor(R.color.colorFontGray1));
                    mHandler.sendEmptyMessageDelayed(RESETTEXT, 1000);
                    if (time <= -1) {
                        mHandler.removeMessages(RESETTEXT);
                        tv_smsfast_login_getverficode.setText(R.string.huoquyanzhen);
                        tv_smsfast_login_getverficode.setEnabled(true);
                    }
            }
        }
    };
    private LinearLayout ll_new_login_back;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ShareSDK.initSDK(this);
        //设置允许使用转场动画
        getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_smsfast_login);
        ((GlobalApplication) getApplication()).getActivityManager().addActivity("SMSFastLoginActivity", this);
        boolean mIslogin = ((GlobalApplication) getApplication()).isLogin();
        Intent intent = getIntent();
        if (intent != null) {
            isCanBack = intent.getBooleanExtra("isCanBack", true);
        }
        User user = DataWareHourse.getInstance().getmUser();
        int i_id = 0;
        if (user != null) {
            i_id = user.getData().get(0).getI_Id();
        } else {
            try {
                user = CacheUtils.readObjectFromTextFile(RequestCode.TOLOGIN_ACTIVITY_REQUESTCODE, User.class);
                if (user != null) {
                    i_id = user.getData().get(0).getI_Id();
                    saveUserInfo(user);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (mIslogin && user != null && i_id != 0) {
            setLoginFinishResult(true);
        } else {
            ((GlobalApplication) getApplication()).setLogin(false);
            CacheUtils.setBooleanToCache(this, CacheUtils.islogin, false);
        }
        initView();

    }

    @Override
    protected void onResume() {
        isCanClickable = true;
        super.onResume();
    }

    private void initView() {
        tv_smsfast_login_getverficode = (TextView) findViewById(R.id.tv_smsfast_login_getverficode);
        tiet_smsfast_login_phonenumber = (TextInputEditText) findViewById(R.id.tiet_smsfast_login_phonenumber);
        til_smsfast_login_phonenumber = (TextInputLayout) findViewById(R.id.til_smsfast_login_phonenumber);
        tiet_smsfast_login_verficode = (TextInputEditText) findViewById(R.id.tiet_smsfast_login_verficode);
        til_smsfast_login_verficode = (TextInputLayout) findViewById(R.id.til_smsfast_login_verficode);
        btn_smsfast_login = (Button) findViewById(R.id.btn_smsfast_login);
        tv_password_login = (TextView) findViewById(R.id.tv_password_login);
        ll_new_login_back = (LinearLayout) findViewById(R.id.ll_new_login_back);
        imgbtn_smsfast_login_qq = (ImageButton) findViewById(R.id.imgbtn_smsfast_login_qq);
        imgbtn_smsfast_login_wechat = (ImageButton) findViewById(R.id.imgbtn_smsfast_login_wechat);
        imgbtn_smsfast_login_sina = (ImageButton) findViewById(R.id.imgbtn_smsfast_login_sina);
        activity_smsfast_login = (RelativeLayout) findViewById(R.id.activity_smsfast_login);
        btn_smsfast_login.setOnClickListener(this);
        imgbtn_smsfast_login_qq.setOnClickListener(this);
        imgbtn_smsfast_login_wechat.setOnClickListener(this);
        imgbtn_smsfast_login_sina.setOnClickListener(this);
        tv_password_login.setOnClickListener(this);
        tv_smsfast_login_getverficode.setOnClickListener(this);
        if (isCanBack) {
            ll_new_login_back.setVisibility(View.VISIBLE);
        } else {
            ll_new_login_back.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_new_login_back://登录按钮
                finish();
                break;
            case R.id.tv_password_login://登录按钮
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    Explode explode = new Explode();
                    explode.setDuration(1000);
                    getWindow().setExitTransition(explode); //出去的动画
                    getWindow().setEnterTransition(explode); //进来的动画
                    //如果有共享元素，可以设置共享元素，那么它就会按照共享元素动画执行，其他的子View就会按照Explode动画执行
                    ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(this);
                }
                Intent intent = new Intent(this, NewPassWordLoginActivity.class);
                startActivityForResult(intent, PSWLOGIN);
                break;
            case R.id.tv_smsfast_login_getverficode://获取验证码
                String phoneNumber = tiet_smsfast_login_phonenumber.getText().toString().trim();
                if (TextUtils.isEmpty(phoneNumber)) {
                    CUtils.showToast("手机号码不能为空！");
                    return;
                }
                if (!Utils.isPhone(phoneNumber)) {
                    CUtils.showToast("手机号码格式有误！");
                    return;
                }
                boolean networkAvailable = NetStatusUtil.isNetworkAvailable(this);
                if (networkAvailable) {
                    time = 60;
                    mHandler.sendEmptyMessage(RESETTEXT);
                    tv_smsfast_login_getverficode.setEnabled(false);
                    getVerifiCode(phoneNumber);
                } else {
                    CUtils.showToast("网络连接异常，请确认网络正常！");
                }

                break;
            case R.id.btn_smsfast_login://登录按钮
                if (isCanClickable) {
                    submit();
                }
                break;
            case R.id.imgbtn_smsfast_login_qq://QQ
                    qqLogin();
                break;
            case R.id.imgbtn_smsfast_login_wechat://微信
                    weChatLogin();
                break;
            case R.id.imgbtn_smsfast_login_sina://新浪微博
                   sinaLogin();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == PSWLOGIN) {
            setLoginFinishResult(true);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    /**
     * 新浪微博登录
     */
    public void sinaLogin() {
        Platform weibo = ShareSDK.getPlatform(SinaWeibo.NAME);
        //回调信息，可以在这里获取基本的授权返回的信息，但是注意如果做提示和UI操作要传到主线程handler里去执行
        weibo.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                arg2.printStackTrace();
            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                //输出所有授权信息
                String s = arg0.getDb().exportData();
                Log.i("新浪微博", "onComplete: " + s);
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
            }
        });
        //authorize与showUser单独调用一个即可
        // weibo.authorize();//单独授权,OnComplete返回的hashmap是空的
        weibo.showUser(null);//授权并获取用户信息
        //移除授权
        //weibo.removeAccount(true);
    }

    /**
     * QQ登录
     */
    public void qqLogin() {
        Platform weibo = ShareSDK.getPlatform(QQ.NAME);
        //回调信息，可以在这里获取基本的授权返回的信息，但是注意如果做提示和UI操作要传到主线程handler里去执行
        weibo.setPlatformActionListener(new PlatformActionListener() {

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                arg2.printStackTrace();
            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                //输出所有授权信息
                String s = arg0.getDb().exportData();
                Log.i("QQ", "onComplete: " + s);
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
            }
        });
        //authorize与showUser单独调用一个即可
        // weibo.authorize();//单独授权,OnComplete返回的hashmap是空的
        weibo.showUser(null);//授权并获取用户信息
        //移除授权
        //weibo.removeAccount(true);
    }

    /**
     * 微信登录
     */
    public void weChatLogin() {
        Platform weibo = ShareSDK.getPlatform(Wechat.NAME);
        //回调信息，可以在这里获取基本的授权返回的信息，但是注意如果做提示和UI操作要传到主线程handler里去执行
        weibo.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                arg2.printStackTrace();
            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                //输出所有授权信息
                String s = arg0.getDb().exportData();
                Log.i("微信", "onComplete: " + s);
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {
            }
        });
        //authorize与showUser单独调用一个即可
        // weibo.authorize();//单独授权,OnComplete返回的hashmap是空的
        weibo.showUser(null);//授权并获取用户信息
        //移除授权
        //weibo.removeAccount(true);
    }

    /**
     * @param finishActivity 这个是用来给启动页面进入后登录用到的，如果是启动页面登录后，需要关闭，其他页面用不到,随便逛逛则不能关闭登录页面
     */
    private void setLoginFinishResult(boolean finishActivity) {
        if (isCanBack) {//如果不是从启动页面进来的，其他页面是可以返回结果并销毁页面
            setResult(LOGIN_OK);
            finish();
            MyActivityManager myActivityManager = ((GlobalApplication) getApplication()).getActivityManager();
            myActivityManager.finishActivity("SMSFastLoginActivity");
        } else {//启动页面登录后直接去主页面即可
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            if (finishActivity) {
                finish();
            }
        }
    }

    /**
     * 请求验证码
     */
    public void getVerifiCode(String phoneNumber) {
        //请求参数
        String url = Url.VERFICATIONCODE + MD5Util.getMD5String(phoneNumber + "00dl")
                + "&Mobile=" + phoneNumber + "&type=dl";
        HttpRequestBean requestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url, SMSFastLoginActivity.this, VerifiCodeLoginBean.class, Url.VERFICATIONCODE);
        HttpHandleUtil.executeCommonPost(SMSFastLoginActivity.this, requestBean);
    }

    /**
     * 提交登录
     */
    private void submit() {
        String verifyCode = tiet_smsfast_login_verficode.getText().toString().trim();
        String phoneNumber = tiet_smsfast_login_phonenumber.getText().toString().trim();
        if (TextUtils.isEmpty(phoneNumber)) {
            CUtils.showToast("手机号码不能为空！");
            return;
        }
        if (!Utils.isPhone(phoneNumber)) {
            CUtils.showToast("手机号码格式有误！");
            return;
        }
        if (TextUtils.isEmpty(verifyCode)) {
            CUtils.showToast("验证码不能为空！");
            return;
        }
        if (Utils.checkNet(this)) {
            isCanClickable = false;
            mHandler.sendEmptyMessageDelayed(LOGINBTN, 5000);
            String url = Url.MEMBERLOGIN + MD5Util.getMD5String(phoneNumber + "00" + verifyCode) + "&nvc_MobilePhone=" + phoneNumber + "&nvc_PassWord=" + verifyCode;
            HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                    SMSFastLoginActivity.this, User.class, Url.MEMBERLOGIN);
            HttpHandleUtil.executeCommonPost(SMSFastLoginActivity.this, httpRequestBean);
        } else {
            CUtils.showToast("请检查网络！");
        }
    }

    /**
     * 保存用户信息
     *
     * @param user
     */
    private void saveUserInfo(User user) {
        if (user != null) {
            DataWareHourse.getInstance().setmUser(user);
            User.DataBean dataBean = user.getData().get(0);
            ((GlobalApplication) getApplication()).setLogin(true);
            CacheUtils.setBooleanToCache(this, CacheUtils.islogin, true);
            CacheUtils.saveObjectToTextFile(RequestCode.TOLOGIN_ACTIVITY_REQUESTCODE, user);
            CacheUtils.setStringToCache(this, CacheUtils.phoneNum, dataBean.getNvc_MobilePhone());
            CacheUtils.setStringToCache(this, CacheUtils.verification, tiet_smsfast_login_verficode.getText().toString().trim());
        }
    }

    /**
     * @param sucessbean 通信成功返回的数据
     */
    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof VerifiCodeLoginBean) {//短信验证码
            VerifiCodeLoginBean response = (VerifiCodeLoginBean) data;
            if (response != null && response.getResCode() != null) {
                if (response.getResCode().equals("0000")) {
                    CUtils.showToast("验证码发送成功，请注意查收");
                } else {
                    mHandler.sendEmptyMessage(GETVERIFIFAIL);
                    CUtils.showToast(response.getMsg());
                }
            }
        } else if (data instanceof User) {
            User userBean = (User) data;
            switch (userBean.getResCode()) {
                case "0000":
                    ((GlobalApplication) getApplication()).setLogin(true);
                    CUtils.showToast("登录成功");
                    saveUserInfo(userBean);
                    setLoginFinishResult(true);
                    break;
                default:
                    if (userBean.getMsg().equals("登陆失败,请检查账号密码是否正确")) {
                        CUtils.showToast("验证码错误");
                    } else {
                        CUtils.showToast(userBean.getMsg());
                    }

                    mHandler.sendEmptyMessage(LOGINBTN);
                    break;
            }
        }
    }

    /**
     * @param errorBean 通信失败返回的数据
     */
    @Override
    public void onError(ErrorBean errorBean) {
        if (errorBean != null && errorBean.getRequestCode().equals(Url.VERFICATIONCODE)) {//获取短信失败
            mHandler.sendEmptyMessage(GETVERIFIFAIL);
        }
        if (errorBean != null && errorBean.getRequestCode().equals(Url.MEMBERLOGIN)) {//登录
            mHandler.sendEmptyMessage(LOGINBTN);
        }

        CUtils.showToast("请求数据错误，请稍后再试！");
    }

    /**
     * 再按一次退出
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (!isCanBack) {
                if (!mExitFlag) {
                    Toast.makeText(this, R.string.dblclick_to_exit, Toast.LENGTH_SHORT).show();
                    mExitFlag = true;
                    mHandler.sendEmptyMessageDelayed(WHAT_EXIT_FLAG, 2000);
                    return true;
                } else if (mExitFlag) {
                    ((GlobalApplication) getApplication()).getActivityManager().exitApp();
                }
            }
        }
        return super.onKeyUp(keyCode, event);
    }
}
